/* eslint-disable no-param-reassign */
import Toast from 'tdesign-miniprogram/toast/index'
import { addToCart } from '../../../services/cart/cart'

const app = getApp()
Page({
  data: {
    goodsList: [],
    keywords: '',
    loading: true,
  },

  onLoad(options) {
    const { searchValue = '' } = options || {};
    this.setData({ keywords: searchValue },() => {
      this.saveHistory()
      this.init();
    });
  },
  
  saveHistory(){
    let historyArr = wx.getStorageSync('historyWords')
    let _historyArr = historyArr || []
    _historyArr.indexOf(this.data.keywords) == -1 ? _historyArr.push(this.data.keywords): ''
    console.log(_historyArr.indexOf(this.data.keywords));
    wx.setStorageSync('historyWords', _historyArr)
  },
  
  init() {
    const db = wx.cloud.database()
    db.collection('book-list').where(db.command.or([
      {
        title: db.RegExp({
          regexp: this.data.keywords,
          options: 'i'
        })
      },
      {
        author: db.RegExp({
          regexp: this.data.keywords,
          options: 'i'
        })
      }
    ])).get({
      success:res=>{
        this.setData({
          loading: false,
          goodsList: res.data
        })
      }
    })
  },

  handleSubmit() {
    this.setData({ goodsList: [], loading: true },() => {
      this.saveHistory()
      this.init();
    });
  },

  inputChange(e){
    this.setData({
      keywords: e.detail.value
    })
  },

  handleAddCart(e) {
    if(app.globalData.userInfo){
      addToCart(app.globalData.userInfo._id, e.detail.goods)
    }else{
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请先前往个人中心登录',
        duration: 1000,
      });
    }
  },

  gotoGoodsDetail(e) {
    const { index } = e.detail;
    const { _id } = this.data.goodsList[index];
    wx.navigateTo({
      url: `/pages/goods/details/index?spuId=${_id}`,
    });
  },
});
